#!/usr/bin/python -S
"""
demo.py

Random demos of Python Unix APIs
"""

__author__ = 'Andy Chu'


import sys



def StartSubprocess():
  import subprocess
  find = subprocess.Popen(['find', '..'], stdout=subprocess.PIPE)
  fd1 = find.stdout.fileno()
  print 'find PID', find.pid

  seq = subprocess.Popen(['seq', '100000'], stdout=subprocess.PIPE)
  fd2 = seq.stdout.fileno()
  print 'seq PID', seq.pid
  return fd1, fd2

FILE = '/home/andy/hg/scrabbly/ospd4.txt'

def StartPopen():
  # this is only 37k; so it can just reside in the pipe!  it exits immediately.
  # The other one is 640k, so it needs many iterations.

  p = popen2.Popen3('find ..')
  fd1 = p.fromchild.fileno()
  print 'find PID', p.pid

  p = popen2.Popen3('seq 100000')
  fd2 = p.fromchild.fileno()
  print 'seq PID', p.pid
  return fd1, fd2


def SelectTest(argv):
  """Returns an exit code."""

  signal.signal(signal.SIGCHLD, SigchldHandler)
  #fd1, fd2 = StartPopen()
  fd1, fd2 = StartSubprocess()

  f = open(FILE)
  fd3 = f.fileno()
  print 'DISK fd', fd3

  while True:
    r, w, e = select.select([fd1, fd2, fd3], [], [])
    # THIS doesn't fucking work, it always returns TRUE, so the os.read() call
    # is blocking!
    for fd in r:
      print '%s ready to read' % fd
      chunk = os.read(fd, 80)
      print '>', repr(chunk)

    print 'sleeping'
    time.sleep(2)


def BlockTest(argv):
  p = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  fd = p.stdin.fileno()

  # os.write will block forever if we write 70000 bytes (more than PIPE_SIZE),
  # and nobody is reading from the pipe yet
  # set it to NONBLOCKING here so this doesn't happen
  fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)

  size = int(argv[2])
  n = os.write(fd, 'b'*size)
  print 'wrote', n , 'bytes'
  out_fd = p.stdout.fileno()
  s = os.read(out_fd, size)
  print 'got', len(s), 'bytes'


def SocketTest(argv):
  io_loop = ioloop.IOLoop.instance()
  callback = functools.partial(connection_ready, sock)
  io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
  io_loop.start()

